/**
  * @description: 热力图
  * @author: hj
  * @update: hj(2020-01-14)
  */

import React, { Component } from 'react';
import styles from './index.module.scss';
import { getMediaById } from '@/service/Api/Chart';
import { observer,inject,Provider } from 'mobx-react';
import './js/map.js'; // 创建地图
import { Select } from '@alifd/next';


const Option = Select.Option;



@inject('chartStore') 
@observer


class HeatMap extends Component {
    constructor(props) {
        super(props);
        this.state = {
            params: [],
            data: [],
            forceFit: true, //forceFit自动试用宽度，默认false
            width: this.props.data.width ? this.props.data.width : '100%',   // 固定宽度    当自适应宽度开启，此功能失效
            height: this.props.data.height ? this.props.data.height : '100%',
            condition: this.props.data.condition ? this.props.data.condition : '',
            pageFlag: this.props.data.pageFlag ? this.props.data.pageFlag : '',
            nofirst: this.props.data.nofirst ? this.props.data.nofirst : '',
            color: this.props.data.color,
            title: '',
            chartId: this.props.data.chartId,
            id: this.props.data.componentId,
            chartData: [],
            axisArr: {},
            haveData: false,

            // 地图数据
            mapData: {
                area: '',
                data: []
            },

            dataNull: false, // 暂无数据

            // 全局变量
            mainData: [], // 操作组件可操作数据
            mainName: '', // 操作组件可操作当前维度
            mainFlag: false, // 是否是操作组件
        };
    };


    componentWillMount() { //初始化
        const _this = this;
        
        // 预览界面
        if (_this.state.pageFlag == 'preview') {
            // 判断当前组件是否是可操作组件
            const { globalData } = _this.props.chartStore;
            if (globalData.slice().length > 0) {
                globalData.slice().map((item,index) => {
                    if (item.affect == _this.state.chartId) { // 可操作组件
                        let affectName = item.affectDimension;
                        _this.setState({
                            mainFlag: true,
                            mainName: affectName
                        })
                    }
                })
            }

            _this.interfaceRequest(_this.state.chartId,_this.state.condition);
        } else { // 配置面板
            if (_this.state.nofirst == 'nofirst') {
                _this.saveHandleData();
            } else {
                _this.interfaceRequest(_this.state.chartId,_this.state.condition);
            }
        }
    }

    // 钩子函数--组件挂载完成后
    componentDidMount() { //初始化
        this.setState({
            haveData: true
        })
    }
    // 接收父组件的数据改变
    componentWillReceiveProps = (nextProps) => {
        const _this = this;
        const { globalData } = _this.props.chartStore;

        // 预览界面---判断是否是变化组件
        if (nextProps.data.pageFlag == 'preview') {
            if (nextProps.data.condition != this.props.data.condition && globalData.slice().length > 0) {
                globalData.slice().map((item,index) => {
                    if (item.affectFlag && item.require == nextProps.data.chartId) { // 联动组件
                        let key = item.requireDimension;
                        let condition = {};
                        Object.keys(nextProps.data.condition).forEach(function(keys){
                            condition[key] = nextProps.data.condition[keys];
                        })
                        _this.interfaceRequest(nextProps.data.chartId,condition);
                    }
                })
            }
        }
    }

    // 数据接口请求
    interfaceRequest = (chartId,condition) => {
        let data = {
            charId: chartId,
            condition: condition
        };
        this.getMediaById(data);
    }
    
    // 数据存储刷新
    saveHandleData = () => {
        const { chartArrData } = this.props.chartStore;
        if (chartArrData.slice().length > 0) {
            chartArrData.slice().map((item) => {
                if (item.id == this.state.chartId) {
                    this.setState({
                        haveData: false
                    },function() {
                        // 数据处理
                        this.handleData(item.data);
                    })
                }
            })
        }
    }

    async getMediaById(data) {
        const res = await getMediaById(data);
        if (res.data && res.data.code === 0) {
            let str = res.data;
            if (str.data && str.data.data && str.data.data.length > 0) {
                // 存储图例原始数据
                const { saveChartData } = this.props.chartStore;
                let oldData = {
                    id: this.state.chartId,
                    data: str.data.data
                }
                saveChartData(oldData);

                // 数据处理
                this.handleData(str.data.data);
            } else {
                this.drawMap();
            }
        }
    }
    // 数据处理
    handleData = (storeAllData) => {
        let storeData = storeAllData[0];
        const _this = this;

        // 存储可操作组件数据
        if (storeData.affect && storeData.affect.length > 0) {
            let obj = {
                id: this.state.chartId,
                label: storeData.title,
                dimensionData: []
            }
            const { saveAffectData } = this.props.chartStore;

            let dimensionData = [];
            storeData.affect.slice().map((item,index) => {
                dimensionData.push(item);
            })
            obj.dimensionData = dimensionData;
            saveAffectData(obj);

            let newNameData = [];
            let mainName = this.state.mainName;
            storeData.data.map((item,index) => {
                Object.keys(item).forEach(function(key){
                    if (key == mainName) {
                        newNameData.push(item[key]);
                    }
                })
            })
            console.log('VectoeMap----',newNameData);
            this.setState({
                mainData: newNameData
            })
        }
        // 存储联动组件数据
        if (storeData.requires && storeData.requires.length > 0) {
            let obj = {
                id: this.state.chartId,
                label: storeData.title,
                dimensionData: []
            }
            const { saveRequireData } = this.props.chartStore;

            let dimensionData = [];
            storeData.requires.slice().map((item,index) => {
                dimensionData.push(item);
            })
            obj.dimensionData = dimensionData;
            saveRequireData(obj);
        }

        _this.setState({
            title: storeData.title
        })
        _this.drawMap(); // 热力图
    }
    


    // 绘制地图
    drawMap = () => {
        const _this = this;
        
        let mapId = 'chart_'+this.state.id+'_'+this.state.chartId;
        createHeatMap(mapId);
    }

    // 绘制闪点地图
    drawScatterMap = () => {
        const _this = this;

        let mapDom = 'chart_'+this.state.id+'_'+this.state.chartId;
        //创建地图
        let PointSimplifierMap = new AMap.Map(mapDom, {
            zoom: 13,
            zoomEnable: false,
        });
        
        //just some colors
        let colors = ['#2c7bb6', '#abd9e9','#ffffbf', '#fde468', '#d7191c' ];

        AMapUI.load(['ui/misc/PointSimplifier', 'lib/$'], function(PointSimplifier, $) {

            if (!PointSimplifier.supportCanvas) {
                alert('当前环境不支持 Canvas！');
                return;
            }

            let pointSimplifierIns = new PointSimplifier({
                zIndex: 15,
                autoSetFitView: false,
                map: PointSimplifierMap, //所属的地图实例

                getPosition: function(item) {
                    if (!item) {
                        return null;
                    }

                    let parts = item.split(',');

                    return [parseFloat(parts[0]), parseFloat(parts[1])];
                },
                getHoverTitle: function(dataItem, idx) {
                    return '序号: ' + idx;
                },
                //使用GroupStyleRender
                renderConstructor: PointSimplifier.Render.Canvas.GroupStyleRender,
                renderOptions: {
                    eventSupport: false, //禁止事件,对性能更友好
                    //点的样式
                    pointStyle: {
                        fillStyle: null,
                        width: 10,
                        height: 10
                    },
                    topNAreaStyle: null,
                    getGroupId: function(item, idx) {

                        //随机返回一个组ID
                        return Math.ceil(colors.length * Math.random());
                    },
                    groupStyleOptions: function(gid) {

                        //随机设置大小
                        let radius = 2 + 10 * Math.random();

                        return {

                            pointStyle: radius > 0 ? {
                                content: function(ctx, x, y, width, height) {

                                    let p = {
                                        x: x + width / 2,
                                        y: y + height / 2,
                                        radius: radius
                                    };

                                    ctx.beginPath();
                                    let gradient = ctx.createRadialGradient(p.x, p.y, 0, p.x, p.y, p.radius);
                                    gradient.addColorStop(0, "red");
                                    gradient.addColorStop(1, "yellow");
                                    ctx.fillStyle = gradient;
                                    ctx.arc(p.x, p.y, p.radius, Math.PI * 2, false);
                                    ctx.fill();

                                },

                                //fillStyle: colors[gid % colors.length],
                                width: radius * 2,
                                height: radius * 2
                            } : null,
                            pointHardcoreStyle: {
                                width: radius * 2 + 3,
                                height: radius * 2 + 3
                            }
                        };
                    }

                }
            });


            //重复render
            setInterval(function() {
                pointSimplifierIns.render();
            }, 500)


            $('<div id="loadingTip">加载数据，请稍候...</div>').appendTo(document.body);
            $.get('https://a.amap.com/amap-ui/static/data/10w.txt', function(csv) {

                let data = csv.split('\n');

                pointSimplifierIns.setData(data.slice(0, 5000));

                $('#loadingTip').remove();
            });
        });
    }

    // select --change
    onSelectChange = (val) => {
        if (val == '场馆点位分布图') {
            this.drawScatterMap(); // 闪点图
        } else {
            this.drawMap(); // 热力图
        }
    }

    // 改变全局变量
    onGlobalVariable = (val) => {
        if (val == '场馆点位分布图') {
            this.drawScatterMap(); // 闪点图
        } else {
            this.drawMap(); // 热力图
        }
        // this.props.onGlobalVariable(val);
    }



    render() {
        const _this = this;
        let Layer = this.props.layer;

        let cardData = _this.state.chartData;
        let mapData = ['用户活跃度热力分布图','场馆点位分布图'];
        let choiceData = mapData;

        return (
            <div id={this.state.id+'_'+this.state.chartId} style={{zIndex: 9999,width: this.state.width,height: this.state.height,overflow: 'hidden',padding: '3%'}}>
                <Layer width={this.state.width} title={this.state.title} chartId={this.state.chartId} choiceData={choiceData} onGlobalVariable={this.onGlobalVariable}></Layer>
                {/* <Select defaultValue="用户活跃度热力分布图" onChange={this.onSelectChange} style={{width: '94%',height: '30px',marginTop: '30px',position: 'absolute',zIndex: 1}}>
                    {mapData.length > 0 && mapData.map((item,index) => {
                        return (
                            <Option value={item} key={item}> {item} </Option>
                        )
                    })}
                </Select> */}
                <div className={styles.mapBox}  id={'chart_'+this.state.id+'_'+this.state.chartId} style={{height: this.state.height - 80,marginTop: '30px',}}></div>
            </div>

        )
    }


}
export default HeatMap;

